/* Copyright 2008 Shawn C. Dodd

This file is part of TagFC.  TagFC is free software: you can redistribute i
t and/or modify it under the terms of the GNU Affero General Public License
 as published by the Free Software Foundation, either version 3 of the Lice
nse, or (at your option) any later version.

TagFC is distributed in the hope that it will be useful, but WITHOUT ANY WA
RRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more 
details.

You should have received a copy of the GNU Affero General Public License al
ong with TagFC.  If not, see <http://www.gnu.org/licenses/>. */

import groovy.xml.MarkupBuilder;
import groovy.xml.StreamingMarkupBuilder;

class PoweredController {

	def quartzScheduler			// injected

	def index = { redirect(action:'by') }

	def by = {
		render 'TFC is powered by audiognomes.com/gnometones.'
	}

	def version = {
		String md = grailsApplication.metadata
		md += '\n'
		render(text:md,contentType:"text/plain")
	}

	def pcount = { 
		render { html() {
		head() { title("Work Piece Summary") }
		body(style:"margin:1.5em;") {
			h3("Work Piece Summary")
			ul() {
				li("Total Piece count, all states: ${Piece.count()}")
				li("Tagged Pieces: ${Piece.countByState('tagged')}")
				li("Unprocessed Pieces: ${Piece.countByState('unproc')}")
//				li("")

			}
		}
		}
		}
	}

	def nik = {
		session.nickname = "cheez"
		render "Your new nickname is ${session.nickname}."
	}

	def getDetail(jobName, jobGroupName) { quartzScheduler.getJobDetail(jobName,jobGroupName) }

	def getTriggers(jobName, jobGroupName) { 
		quartzScheduler.getTriggersOfJob(jobName,jobGroupName) as String[] 
	}

	def getFirstTriggerFire(jobName, jobGroupName) {	// show the earliest of fire times in the future
	        quartzScheduler.getTriggersOfJob(jobName,jobGroupName)[0].getNextFireTime()
	}

	def quartz = {
		def jgn = "TagFC"
		def jn = quartzScheduler.getJobNames(jgn)

		// check for form post, handle command
		if(params.containsKey("triggerJob")) {
			quartzScheduler.triggerJobWithVolatileTrigger(params.jobName, params.groupName)
		} else if(params.containsKey("toggleSched")) {
			if( quartzScheduler.isPaused() ) {
				quartzScheduler.start()
			} else {
				quartzScheduler.pause()
			}
		} else if(params.containsKey("pauseTrigs")) {
                	quartzScheduler.pauseAll()
		} else if(params.containsKey("resumeTrigs")) {
			quartzScheduler.resumeAll()
		}

		// summarize scheduler state
		def writer = new StringWriter()
		def builder = new MarkupBuilder(writer)
		builder.html { 
			head { 
				title("Batch Job Scheduler Control") 
				style(type:"text/css") { mkp.yieldUnescaped('''
''')
				}
			} 
			body {
			div {
				span("Scheduler is currently ${quartzScheduler.isPaused()?'Paused':'Running'}: ") {
				builder.form(id:"f1", class:"row", action:"quartz", method:"post") {
					input(type:"hidden", name:"toggleSched") 
					input(type:"submit", value:"toggle")
				}
				}
				span("All triggers:") {
				builder.form(id:"f2", class:"row", action:"quartz", method:"post") {
				        input(type:"hidden", name:"pauseTrigs")
                                        input(type:"submit", value:"Pause")
				}
				builder.form(id:"f3", class:"row", action:"quartz", method:"post") {
                                        input(type:"hidden", name:"resumeTrigs")
                                        input(type:"submit", value:"Resume")
                                }
				}
			}
			div(id:"note", "Summary of the batch jobs in the Quartz scheduler:")
			div() {
			table {
				builder.tr {
					builder.th('Job Name')
					builder.th('Next Scheduled Trigger Date')
					builder.th() { mkp.yieldUnescaped('&nbsp;') }
				}
				for (n in jn) {		// loop over configured jobs
					tr {
						td(n)
						td(getFirstTriggerFire(n,jgn))
						td { 
						builder.form(action:"quartz", method:"post") {
							input(type:"hidden", name:"triggerJob")
							input(type:"hidden", name:"jobName", value:n)
							input(type:"hidden", name:"groupName", value:jgn)
							input(type:"submit", value:"trigger now")
						}
						}
					}
				}
			}
			}
		}}
		//println writer.toString()
		render(text:writer.toString())
	}
}
